package com.evon.yardmanagement.ui.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;

import com.evon.yardmanagement.model.Action;
import com.evon.yardmanagement.model.Role;
import com.evon.yardmanagement.security.YardSecurityManager;
import com.evon.yardmanagement.service.RoleManagementService;
import com.evon.yardmanagement.ui.dto.ActionDTO;
import com.evon.yardmanagement.ui.dto.RoleDTO;
import com.opensymphony.xwork2.ActionSupport;

public class RoleDetailsAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private RoleDTO selectedRole;
	private List<ActionDTO> listActions = new ArrayList<ActionDTO>();
	private int selectedRoleId;
	List<Integer> selectedAllowedAction = new ArrayList<Integer>();

	public String execute() {
		listActions = RoleManagementService.getAllActions();

		if (selectedRoleId <= 0) {
			return SUCCESS;
		}
		selectedRole = RoleManagementService.getRole(selectedRoleId);
		if (selectedRole != null) {
			for (ActionDTO action : selectedRole.getAllowedAction()) {
				selectedAllowedAction.add(action.getId());
			}
		}
		return SUCCESS;

	}

	public String save() {
		
		listActions = RoleManagementService.getAllActions();
		
		List<ActionDTO> selectedActions = new ArrayList<ActionDTO>();
		if (selectedAllowedAction != null || !selectedAllowedAction.isEmpty()) {
			for (Integer actionId : selectedAllowedAction) {
				ActionDTO action = new ActionDTO();
				action.setId(actionId);
				selectedActions.add(action);
			}
		}else{
			addActionError("Please select permitted action for role");
		}
		selectedRole.setAllowedAction(selectedActions);
		if(selectedRole.getName() == null || selectedRole.getName().trim().equals("")){
			addActionError("Please enter role name");
		}
		
		RoleManagementService.save(selectedRole);
		return SUCCESS;
	}

	public RoleDTO getSelectedRole() {
		return selectedRole;
	}

	public void setSelectedRole(RoleDTO selectedRole) {
		this.selectedRole = selectedRole;
	}

	public List<ActionDTO> getListActions() {
		return listActions;
	}

	public void setListActions(List<ActionDTO> listActions) {
		this.listActions = listActions;
	}

	public int getSelectedRoleId() {
		return selectedRoleId;
	}

	public void setSelectedRoleId(int selectedRoleId) {
		this.selectedRoleId = selectedRoleId;
	}

	public List<Integer> getSelectedAllowedAction() {
		return selectedAllowedAction;
	}

	public void setSelectedAllowedAction(List<Integer> selectedAllowedAction) {
		this.selectedAllowedAction = selectedAllowedAction;
	}
}
